package com.yiding.sys.common;

import com.yiding.sys.common.anotation.IgnoreControllerAdvice;
import com.yiding.sys.common.model.PageResult;
import com.yiding.sys.common.model.Result;
import com.yiding.sys.common.enums.ResultCodeEnum;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "com.yiding.sys.controller")
public class GlobalResponseAdvice implements ResponseBodyAdvice {

	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		if (returnType.getExecutable().isAnnotationPresent(IgnoreControllerAdvice.class)) {
			IgnoreControllerAdvice ica = returnType.getExecutable().getAnnotation(IgnoreControllerAdvice.class);
			if (ica.isIgnore()) {
				// 如果被@IgnoreControllerAdvice注解标注，并且isIgnore属性为true，则直接返回，不对body做任何处理
				return body;
			}
		}

		if (body instanceof String) {
			return new Result<>().setData(body).setMsg(ResultCodeEnum.SUCCESS.getName());
		}

		// 如果已经封装为Result，则直接返回，避免二次封装. 判断PageResult的原因是防止对PageResult二次封装，导致layui数据格式不适配
		if (body instanceof Result || body instanceof PageResult || body instanceof ModelAndView) {
			return body;
		}
		return new Result<>().geneSuccess(body);
	}
}
